package com.cindata

import grails.converters.JSON
import grails.plugin.springsecurity.annotation.Secured
import grails.transaction.Transactional

import static org.springframework.http.HttpStatus.*

@Secured(['isAuthenticated()'])
@Transactional
class UserController
{
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE", appLogin: "POST", appQueryUser: "POST"]

    def userService
    def passwordEncoder
    def liquidityRiskReportService
    def springSecurityService

    def index(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        max = params.max
        def sort = params['sort']
        def order = params['order']
        def offset = params.offset
        def sql = " select new map (u.id as id, u.username as username, u.fullName as fullName, u.cellphone as cellphone, u.enabled as enabled, u.createdDate as createdDate, u.account.name as accountname, u.expiredDate as expiredDate, u.skin as skin) from User u where 1 =1 "
        if (order && sort)
        {
            sql += " order by u.${sort} ${order}"
        }
        else
        {
            sql += " order by u.modifiedDate desc "
        }
        def sql1 = " select count(*) from User"
        def userList = User.executeQuery(sql, [max: max, offset: offset]).asList()
        def roleName = ""
        userList.each { Map params ->
            def roleNames = ""
            def sql2 = " select new map (ur.user as user ,r.name as rolename) from UserRole as ur, Role as r where ur.role= r.id and ur.user = " + params.get("id")
            def roleNamesList = UserRole.executeQuery(sql2).asList()
            roleNamesList.each {
                roleNames += it.rolename + ","
            }
            if (roleNames)
            {
                roleName = roleNames.toString().substring(0, roleNames.length() - 1)
            }
            else
            {
                roleNames = ""
            }

            params.put("roleName", roleName)

        }
        def count = User.executeQuery(sql1)
        respond userList, model: [userList: userList, userCount: count[0]]
    }

    @Transactional
    def searchUser()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def sort = params['sort']
        def order = params['order']
        def fullName = params["fullName"]
        def username = params["username"]
        def enabled = params["enabled"]

        def sql = " select new map (u.id as id ,u.username as username,u.fullName as fullName,u.cellphone as cellphone,u.enabled as enabled ,u.createdDate as createdDate, u.account.name as accountname, u.expiredDate as expiredDate ,u.skin as skin )" + " from User u   where 1 = 1 "
        def sql1 = " select count(*) from User u where 1=1 "
        if (fullName)
        {
            sql += " and u.fullName like '%${fullName}%'"
            sql1 += " and u.fullName like '%${fullName}%'"
        }
        if (username)
        {
            sql += " and u.username like '%${username}%'"
            sql1 += " and u.username like '%${username}%'"
        }
        if (enabled)
        {
            sql += " and u.enabled is '${enabled}'"
            sql1 += " and u.enabled is '${enabled}'"
        }
        if (order && sort)
        {
            sql += " order by u.${sort} ${order}"
        }
        else
        {
            sql += "order by u.username desc "
        }

        def max = params.max
        def offset = params.offset

        def userList = User.executeQuery(sql, [max: max, offset: offset]).asList()
        def roleName = ""
        userList.each { Map params ->
            def roleNames = ""

            def sql2 = " select new map (ur.user as user ,r.name as rolename ) from UserRole as ur , Role as r where ur.role= r.id and ur.user = " + params.get("id")
            def roleNamesList = UserRole.executeQuery(sql2).asList()
            roleNamesList.each {
                roleNames += it.rolename + ","
            }
            if (roleNames)
            {
                roleName = roleNames.toString().substring(0, roleNames.length() - 1)
            }
            else
            {
                roleNames = ""
            }
            params.put("roleName", roleName)

        }

        def count = User.executeQuery(sql1)

        def user = new User(params)

        respond userList, model: [userList: userList, userCount: count[0], user: user, params: params], view: 'index'
    }

    def show(User user)
    {
        def userRoleList = UserRole.findAllByUser(user)
        respond user, model: [userRoleList: userRoleList]
    }

    def userInfo(User user)
    {
        def role = UserRole.findAllByUser(user).asList()
        def userRoleName = ""
        def userRoleList = ""
        role.each {
            userRoleName += it.role.authority + ","
        }
        if (userRoleName)
        {
            userRoleList = userRoleName.toString().substring(0, userRoleName.length() - 1)
        }
        else
        {
            userRoleList = ""
        }
        params.userRoleList = userRoleList
        respond user, model: [params: params]
    }

    def create()
    {
        respond new User(params), model: [roleList: Role.findAll()]
    }

    @Transactional
    def save(User user)
    {
        if (user == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (user.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond user.errors, view: 'create'
            return
        }

        if (user.validate())
        {
            user.save flush: true
        }
        else
        {
            println user.errors
        }

        def roleList = params["roleList"]
        if (roleList instanceof String)
        {
            roleList = roleList?.split(",")
        }
        roleList.each {
            def userRole = new UserRole()
            userRole.user = user
            userRole.role = Role.findById(it)
            if (userRole.validate())
            {
                userRole.save flush: true
            }
            else
            {
                println userRole?.errors
            }
        }
        redirect action: 'index', method: "GET"
    }

    def edit(User user)
    {
        def role = UserRole.findAllByUser(user).asList()
        def userRoleList = new ArrayList()
        role.each {
            userRoleList.add(it.role.id)
        }
        params.userRoleList = userRoleList
        respond user, model: [params: params]
    }

    /**
     * 用户修改
     * @param user
     * @return
     */
    def modify(User user)
    {
        def role = UserRole.findAllByUser(user).asList()
        def userRoleName = ""
        def userRoleList = ""
        role.each {
            userRoleName += it.role.authority + ","
        }
        if (userRoleName)
        {
            userRoleList = userRoleName.toString().substring(0, userRoleName.length() - 1)
        }
        else
        {
            userRoleList = ""
        }
        params.userRoleList = userRoleList
        respond user, model: [params: params]
    }

    /**
     * 用户修改
     * @param user
     * @return
     */
    @Transactional
    def userModify(User user)
    {
        if (user == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (user.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond user.errors, view: 'edit'
            return
        }

        user.save flush: true
        redirect action: 'index', method: "GET"
    }

    @Transactional
    def update(User user)
    {
        if (user == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (user.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond user.errors, view: 'edit'
            return
        }

        user.save flush: true
        UserRole.executeUpdate("delete UserRole ur where ur.user = :user", [user: user])

        def roleList = params["roleList"]
        if (roleList instanceof String)
        {
            roleList = roleList?.split(",")
        }
        roleList.each {
            def userRole = new UserRole()
            userRole.user = user
            userRole.role = Role.findById(it)
            if (userRole.validate())
            {
                userRole.save flush: true
            }
            else
            {
                println userRole?.errors
            }
        }

        redirect action: 'index', method: "GET"
    }

    @Transactional
    def deleteRole()
    {
        String userId = params["userId"]
        String roleId = params["roleId"]
        def userRole = UserRole.findByUserAndRole(User.findById(userId), Role.findById(roleId))

        if (userRole == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        userRole.delete flush: true

        redirect controller: "user", action: "index", method: "GET"

        /*request.withFormat{
            form multipartForm{
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'userRole.label',
                default: 'userRole')])
                redirect action: "index", method: "GET"

            }
            '*'{render status: NO_CONTENT}
        }*/
    }

    @Transactional
    def delete(User user)
    {

        if (user == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }
        def userRoleList = UserRole.findAllByUser(user)
        userRoleList.each {
            it.delete flush: true
        }
        user.delete flush: true
        flash.message = "用户" + user.fullName + "已经删除成功"

        redirect controller: "user", action: "index", method: "GET"
        //        request.withFormat {
        //            form multipartForm {
        //                flash.message = message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), user.id])
        //                redirect action: "index", method: "GET"
        //            }
        //            '*' { render status: NO_CONTENT }
        //        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label',
                                                                                          default: 'User'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['isAuthenticated()'])
    def changePassword()
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        respond user
    }

    /**
     * 修改密码*/
    @Secured(['isAuthenticated()'])
    @Transactional
    def updatePassword()
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def oldPassword = params['oldPassword']
        def newPassword = params['newPassword']
        if (oldPassword && newPassword)
        {
            //密码不能为空
            if (passwordEncoder.isPasswordValid(user.password, oldPassword, null))
            {
                //原密码匹配成功
                user.password = newPassword
                user.save flush: true //保存新密码
                render([status: "success"] as JSON)
            }
            else
            {
                //flash.message = message(code: '原密码错误，请重新输入')
                // respond user, view: 'changePassword'
                render([status: "error", errorMessage: message(code: '原密码错误，请重新输入')] as JSON)
            }
        }
        else
        {
            render([status: "error", errorMessage: message(code: '密码为空')] as JSON)
        }

    }

    @Secured(['isAuthenticated()'])
    @Transactional
    def resetPassword()
    {
        def id = params["id"]
        def user = User.findById(id)
        respond user
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['isAuthenticated()'])
    @Transactional
    def passwordReset(User user)
    {
        def password = params['newPassword']
        def destination = params['destination']
        user.password = password
        if (user.validate())
        {
            user.save flush: true
            flash.message = "密码重置成功"
            if (destination)
            {
                redirect controller: destination, action: 'index'
            }
            else
            {
                redirect action: 'index'
                return
            }
        }
        else
        {
            flash.message = user.errors
            if (destination)
            {
                redirect controller: destination, action: 'index'
            }
            else
            {
                redirect action: 'index'
            }
        }
    }

    def changeSkin()
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        user.skin = params['skin'].toInteger()
        user.save()

        render([status: "success"] as JSON)
    }
}
